#include <string.h>
#include <windows.h>
#include "lib.h"
#include "stream.h"

#include "pchmfest.h"
#include "pkg.h"
#include "mfestprv.h"
#include "zipfile.h"

#define TEMPFILE "pchu0001.tmp"

//
// ---------------------- PatchPackageManifest
//
// Exactly like PkgMakerPackageManifest (in client/lobby/pkgmkr) w/o save.
//
// All pathnames stored within the manifest use Unix separators ('/').
//
bool8
PatchPackageManifest::load(PackageManagement::Package& pkg, class ZipFile& zf)
{
	ZipEntry* probe;
	pCStream destMFest = (pCStream)0;
	UnzipStream* srcMFest = (UnzipStream*)0;
	uint8 buf[4096];
	int32 amt;
	PMHead pmh;
	PMPackage pmp;

	probe = zf.getZipEntries();
	while (probe)
//		if (probe->filename && strstr((char*)probe->filename, "installed/"))
	if (probe->filename.find("installed/") != String::NPOS)
			break;
		else
			probe = probe->getNext();

	if (!probe)
		goto abort;

	destMFest = newCStream(TEMPFILE, 0);
	if (!destMFest)
		goto abort;

	srcMFest = probe->getUnzipStream(&zf);
	if (!srcMFest)
		goto abort;

	while ((amt = srcMFest->read(buf, 4096)) >= 0)
		if (amt > 0 && amt != CStreamWrite(destMFest, buf, amt))
		{
			amt = -2;
			break;
		}

	if (amt < -1)	// problem writing
		goto abort;
	
	delete srcMFest;
	srcMFest = (UnzipStream*)0;

	// read mfest into pkg
	//
	if (streamEOF == CStreamSeek(destMFest, 0, streamSEEK_SET))
		goto abort;

	if (!pmh.load(destMFest))
		goto abort;

	if (pmh.NumPkgs != 1)
		goto abort;

	if (!pmp.load(destMFest, pmh, &pkg))
		goto abort;

	deleteCStream(destMFest);
	CStreamDelFile((char*)(const char*)TEMPFILE);

	return true;

abort:
	delete srcMFest;
	deleteCStream(destMFest);
	CStreamDelFile((char*)(const char*)TEMPFILE);

	return false;
}
